export default function (store, opts = {}) {

  const {moduleName = 'loading'} = opts;
  const start = 'ACTION_START';
  const end = 'ACTION_END';
  let isRegister = true;

  store.registerModule(moduleName, {
    namespaced: true,
    state: {},
    mutations: {
      [start] (state, action) {
        state[action] = true;
      },
      [end] (state, action) {
        state[action] = false;
      }
    }
  });

  store.subscribeAction({
    before: (action, state) => {
      if (!isRegister) return;

      const path = action.type;
      if (typeof state[moduleName][path] !== 'boolean') {
        store.replaceState({
          ...store.state,
          [moduleName]: {
            ...store.state[moduleName],
            ...{[path]: false}
          }
        });
      }
      if (state[moduleName][path] !== true) {
        store.commit(`${moduleName}/${start}`, path);
      }
    },
    after: (action, state) => {
      if (!isRegister) return;

      const path = action.type;
      if (state[moduleName][path] !== false) {
        store.commit(`${moduleName}/${end}`, path);
      }
    }
  });

  return {
    options: opts,
    unregister () {
      isRegister = false;
      store.unregisterModule(moduleName);
    }
  }
}
